package cn.edu.cqut.mdm.core.moduleproxy;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;

public class ModuleProxyInitializerForSpring implements BeanPostProcessor{

	@Override
	public Object postProcessBeforeInitialization(Object bean, String beanName)
			throws BeansException {
		Field[] fields = bean.getClass().getDeclaredFields();
		for(Field field : fields){
			Annotation[] annotations = field.getAnnotations();
			for(Annotation annotation : annotations){
				if(annotation.annotationType().equals(ModuleProxy.class)){
					try {
						field.setAccessible(true);
						field.set(bean, ModuleProxyFactory.getProxy(field.getType()));
						System.out.println("为" + beanName + "的" + field.getName() + "字段注入了代理。");
					} catch (IllegalArgumentException e) {
						e.printStackTrace();
					} catch (IllegalAccessException e) {
						e.printStackTrace();
					}
					break;
				}
			}
		}
		return bean;
	}

	@Override
	public Object postProcessAfterInitialization(Object bean, String beanName)
			throws BeansException {
		return bean;
	}


}
